import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PointsRecord } from './entities/points-record.entity';
import { CreatePointsRecordDto } from './dto/create-points-record.dto';
import { UserService } from '../user/user.service';

@Injectable()
export class PointsService {
  constructor(
    @InjectRepository(PointsRecord)
    private pointsRecordRepository: Repository<PointsRecord>,
    private userService: UserService,
  ) {}

  async findAll(query: any): Promise<[PointsRecord[], number]> {
    const { userId, type, page = 1, limit = 10 } = query;
    
    const queryBuilder = this.pointsRecordRepository.createQueryBuilder('pointsRecord');
    
    // 联查用户信息
    queryBuilder.leftJoinAndSelect('pointsRecord.user', 'user');
    
    // 条件过滤
    if (userId) {
      queryBuilder.andWhere('pointsRecord.userId = :userId', { userId });
    }
    
    if (type) {
      queryBuilder.andWhere('pointsRecord.type = :type', { type });
    }
    
    // 分页
    queryBuilder.skip((page - 1) * limit);
    queryBuilder.take(limit);
    
    // 排序
    queryBuilder.orderBy('pointsRecord.createdAt', 'DESC');
    
    return queryBuilder.getManyAndCount();
  }

  async findOne(id: number): Promise<PointsRecord> {
    const record = await this.pointsRecordRepository.findOne({
      where: { id },
      relations: ['user'],
    });
    
    if (!record) {
      throw new NotFoundException(`积分记录ID为${id}的记录不存在`);
    }
    
    return record;
  }

  async findByUserId(userId: number, query: any): Promise<[PointsRecord[], number]> {
    const { type, page = 1, limit = 10 } = query;
    
    const queryBuilder = this.pointsRecordRepository.createQueryBuilder('pointsRecord');
    
    queryBuilder.where('pointsRecord.userId = :userId', { userId });
    
    if (type) {
      queryBuilder.andWhere('pointsRecord.type = :type', { type });
    }
    
    // 分页
    queryBuilder.skip((page - 1) * limit);
    queryBuilder.take(limit);
    
    // 排序
    queryBuilder.orderBy('pointsRecord.createdAt', 'DESC');
    
    return queryBuilder.getManyAndCount();
  }

  async create(createPointsRecordDto: CreatePointsRecordDto): Promise<PointsRecord> {
    const { userId, type, amount } = createPointsRecordDto;
    
    // 先获取用户，并更新用户积分
    const user = await this.userService.findOne(userId);
    
    // 计算积分变动
    const pointsChange = type === '收入' ? amount : -amount;
    await this.userService.updatePoints(userId, pointsChange);
    
    // 获取更新后的余额
    const updatedUser = await this.userService.findOne(userId);
    const balance = updatedUser.points;
    
    // 创建积分记录
    const pointsRecord = this.pointsRecordRepository.create({
      ...createPointsRecordDto,
      balance,
    });
    
    return this.pointsRecordRepository.save(pointsRecord);
  }

  async remove(id: number): Promise<void> {
    const record = await this.findOne(id);
    
    // 撤销积分变动
    const pointsChange = record.type === '收入' ? -record.amount : record.amount;
    await this.userService.updatePoints(record.userId, pointsChange);
    
    await this.pointsRecordRepository.remove(record);
  }
} 